package com.tl.drivers.phone.system.utils;

import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.tl.drivers.phone.MyApplication_;
import com.tl.drivers.phone.R;
import com.tl.drivers.phone.system.bean.BaseRequestEntity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 网络请求工具类
 * <h3>Description</h3>
 * TODO
 * <h3>Author</h3> luzhenbang
 * <h3>Date</h3> 2017/10/24 16:14
 * <h3>Copyright</h3> Copyright (c)2017 Shenzhen TL  Co., Ltd. Inc. All rights reserved.
 */
public class HttpUtil {

    public static final String TAG = HttpUtil.class.getSimpleName();

    public static final MediaType MEDIATYPE = MediaType.parse("application/json; charset=utf-8");
    /** 连接超时*/
    public static final int CONNECT_OUT_TIME = 5000;
    /** 读取超时*/
    public static final int READ_OUT_TIME = 5000;
    /** 写超时*/
    public static final int WRITE_OUT_TIME = 5000;
    /**参数类型 */
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    /**
     * 下载文件
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2017/10/24,16:16
     * <h3>UpdateTime</h3> 2017/10/24,16:16
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param url 文件下载地址
     * @param fileCallBack 文件回调接口
     */
    public static void downFile(String url,FileCallBack fileCallBack) {
        if (TextUtils.isEmpty(url)){
            Log.w(TAG,"url can not null !");
            return;
        }
        if (!NetworkUtil.checkNetworkState(MyApplication_.getInstance())){
            Toast.makeText(MyApplication_.getInstance(),
                    MyApplication_.getInstance().getString(R.string.error_net_exception), Toast.LENGTH_SHORT).show();
            return;
        }
        OkHttpUtils.
                get().
                url(url).
                build().
                connTimeOut(5000).
                execute(fileCallBack);
    }

    /**
     * get请求
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2017/10/24,16:22
     * <h3>UpdateTime</h3> 2017/10/24,16:22
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param url 路径
     * @param stringCallback 回调接口
     */
    public static void get(String url, StringCallback stringCallback){
        if (TextUtils.isEmpty(url)){
            Log.w(TAG,"url can not null !");
            return;
        }
        if (!NetworkUtil.checkNetworkState(MyApplication_.getInstance())){
            Toast.makeText(MyApplication_.getInstance(),
                    MyApplication_.getInstance().getString(R.string.error_net_exception), Toast.LENGTH_SHORT).show();
            return;
        }
        OkHttpUtils
                .get()
                .url(url)
                .build()
                .readTimeOut(5000)
                .connTimeOut(5000)
                .execute(stringCallback);
    }

    /**
     * post请求
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2017/10/24,16:25
     * <h3>UpdateTime</h3> 2017/10/24,16:25
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param url 路径
     * @param parameters  请求参数
     * @param stringCallback 回调接口
     */
    public static void post (String url, Map<String,String> parameters ,StringCallback stringCallback){
        if (TextUtils.isEmpty(url)){
            Log.w(TAG,"url can not null !");
            return;
        }

        if (!NetworkUtil.checkNetworkState(MyApplication_.getInstance())){
            Toast.makeText(MyApplication_.getInstance(),
                    MyApplication_.getInstance().getString(R.string.error_net_exception), Toast.LENGTH_SHORT).show();
            return;
        }

        PostFormBuilder postFormBuilder = OkHttpUtils
                .post()
                .url(url);
        Set<Map.Entry<String ,String>> set = parameters.entrySet();
        Iterator<Map.Entry<String ,String>> it = set.iterator();
        while (it.hasNext()){
            Map.Entry<String,String>  item = it.next();
            postFormBuilder.addParams(item.getKey(),item.getValue());
        }
//        postFormBuilder.params(parameters);
        postFormBuilder
                .build()
                .readTimeOut(5000)
                .connTimeOut(5000)
                .execute(stringCallback);

    }


    /**
     * post请求
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2017/10/24,16:25
     * <h3>UpdateTime</h3> 2017/10/24,16:25
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param url 路径
     * @param entry  请求参数
     * @param callback 回调接口
     */

    public static Call post (String url, BaseRequestEntity entry , Callback callback){
        if (TextUtils.isEmpty(url)){
            Log.w(TAG,"url can not null !");
            return null;
        }
        if (!NetworkUtil.checkNetworkState(MyApplication_.getInstance())){
            Toast.makeText(MyApplication_.getInstance(),
                    MyApplication_.getInstance().getString(R.string.error_net_exception), Toast.LENGTH_SHORT).show();
            return null;
        }
        OkHttpClient okHttpClient = new OkHttpClient()
                .newBuilder()
//                .readTimeout(5000, TimeUnit.MILLISECONDS)
//                .connectTimeout(5000,TimeUnit.MILLISECONDS)
                .build();
        String json = JSON.toJSONString(entry);
        RequestBody requestBody = RequestBody.create(MEDIATYPE, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
        return call;
    }

    /**文件上传
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2018/1/22,10:44
     * <h3>UpdateTime</h3> 2018/1/22,10:44
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param url
     * @param callback
     * @return
     */
    public static void upload (String url ,String token , com.zhy.http.okhttp.callback.Callback callback, File file){
        OkHttpUtils
                .post()
                .url(url)
                .addParams("token",token)
                .addFile("file","",file)
                .build()
                .execute(callback);
    }


    /**
     * 多文件上传
     * (此处输入方法执行任务.)
     * <h3>Version</h3> 1.0
     * <h3>CreateTime</h3> 2018/1/22,15:07
     * <h3>UpdateTime</h3> 2018/1/22,15:07
     * <h3>CreateAuthor</h3> luzhenbang
     * <h3>UpdateAuthor</h3>
     * <h3>UpdateInfo</h3> (此处输入修改内容,若无修改可不写.)
     * @param url
     * @param key
     * @param params
     * @param files
     */
    public static Call upload (String url, String key , HashMap<String ,String> params,File[] files,Callback callback){
        OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .build();
        MultipartBody.Builder multipartBody = new MultipartBody.Builder();
        if (null != params && params.size() > 0){
            Set<Map.Entry<String,String>> entries  = params.entrySet();
            Iterator<Map.Entry<String,String>> iterator = entries.iterator();
            while (iterator.hasNext()){//添加参数
                Map.Entry<String,String> entry = iterator.next();
            multipartBody.addFormDataPart(entry.getKey(),entry.getValue());
//                multipartBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""),
//                        RequestBody.create(null, entry.getValue()));
            }
        }

        RequestBody fileBody = null;
        for (File file : files){
            multipartBody.addFormDataPart(key,file.getName(),RequestBody.create(MEDIA_TYPE_PNG,file));
//            String fileName = file.getName();
//            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
//            //TODO 根据文件名设置contentType
//            // Content-Disposition: form-data; name="file"; filename="1463114525162.jpg"
//            multipartBody.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + fileName + "\""), fileBody);
        }
        RequestBody requestBody = multipartBody.build();
        Request  request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);
        return call;
    }


    private static String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }


}
